<template>
  <el-dialog v-model="visible" fullscreen destroy-on-close @close="handleClose" draggable :loading="loading">
    <template #header>{{ TitleMap[dialogStatus] }}</template>
    <el-form :rules="rules" ref="formRef" :model="modelForm" label-width="100px">
      <el-row :gutter="40">
        <el-col :span="18">
          <el-form-item label="标题" prop="title">
            <el-input v-model="modelForm.title" />
          </el-form-item>
          <el-form-item label="简介" prop="description">
            <el-input v-model="modelForm.description" type="textarea" :rows="2" placeholder="请输入简介" />
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <Tinymce :key="tinymceKey" v-model:value="modelForm.content" style="width: 100%" placeholder="请输入内容" />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-collapse v-model="activeCollapse">
            <el-collapse-item title="文章状态" name="1">
              <el-checkbox v-model="modelForm.status" :true-label="2" :false-label="1">保存草稿</el-checkbox>
            </el-collapse-item>

            <el-collapse-item title="文章类型" name="2">
              <el-row :gutter="20">
                <el-col :span="12">
                  <MyModel :list="modelForm.modelData" :all="false" more-value v-model="state.modelid" @onChange="onModelChange" style="width: 100%" />
                </el-col>
                <el-col :span="12">
                  <el-form-item prop="catid" label-width="0">
                    <el-select v-model="catid" style="width: 100%" placeholder="请选择类别" default-first-option>
                      <el-option v-for="item in state.currentCategories" :key="item.id" :label="item.colTitle" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-collapse-item>

            <el-collapse-item title="封面图" name="3" class="app-collapse-cover">
              <el-form-item prop="smallimg" label-width="0">
                <template v-if="haveSmallImg">
                  <div class="flex flex-col items-center pb-5">
                    <img class="app-blog-form-img" width="400" :src="modelForm.smallimg" alt="" />
                    <div class="app-form-preview">
                      <el-button size="default" type="danger" plain :icon="Delete" @click="handleDelImg">删除</el-button>
                    </div>
                  </div>
                </template>
                <template v-else>
                  <Upload id="cover1" v-model:imageUrl="modelForm.smallimg">
                    <template #tip> 只能上传jpg/png文件，且不超过2MB</template>
                  </Upload>
                </template>
              </el-form-item>
            </el-collapse-item>

            <el-form-item label-width="0" class="pt-5">
              <el-button @click="handleClose">取消</el-button>
              <el-button type="primary" @click="handleSubmit()">确认</el-button>
            </el-form-item>
          </el-collapse>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit()">确认</el-button>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import useLoading from '@/hooks/loading'
import { TitleMap } from '@/config'
import Tinymce from '@/components/Editor/tinymce.vue'
import Upload from '@/components/Upload/index.vue'
import { Delete } from '@element-plus/icons-vue'
// import { isUndefined } from 'lodash'

interface EditProps {
  modelForm: any
  editVisible: boolean
  createData: any
  updateData: any
  setEditVisible: any
  models: any
  title?: string
  dialogStatus: string
}
const props = withDefaults(defineProps<EditProps>(), {
  editVisible: false,
  modelForm: {
    ord: 0,
    title: '',
    description: '',
    smallimg: '',
  },
  models: [],
  title: '',
  dialogStatus: 'create',
  createData: () => {},
  updateData: () => {},
  setEditVisible: () => {},
})
const activeCollapse = ['1', '2', '3']
const { modelForm, models } = toRefs(props)
const { loading, setLoading } = useLoading()
const isEdit = computed(() => props.dialogStatus === 'update')
const formRef = ref<any>(null)
const tinymceKey = ref(1)
const catid = ref(modelForm.value.catid)
const visible = ref(false)
const haveSmallImg = ref(false)
const rules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
}
const state = reactive<any>({
  categories: [],
  currentCategories: [],
  modelid: { modelid: 0 },
})

const filterCategory = (val: any) => {
  const cur = models.value.filter((item: any) => item.modelid === +val)

  if (cur) {
    state.currentCategories = cur
  }

  return cur
}

watch(
  () => props.editVisible,
  (show) => {
    visible.value = show
  }
)

// 初始化分类数据
watch(
  () => modelForm.value.modelData,
  (val: any) => {
    if (!isEdit.value) {
      state.modelid.modelid = val[0].modelid
      modelForm.value.modelid = val[0].modelid
      filterCategory(val[0].modelid)
    } else {
      state.modelid.modelid = modelForm.value.modelid
      filterCategory(modelForm.value.modelid)
      catid.value = modelForm.value.catid
    }
  }
)

// 监测上传状态
watch(
  () => modelForm.value.smallimg,
  (v) => {
    haveSmallImg.value = !!v
  }
)

const onModelChange = (value: any) => {
  filterCategory(value.modelid)
  modelForm.value.catid = null
  catid.value = null
  modelForm.value.modelid = value.modelid
}

const handleClose = () => {
  props.setEditVisible()
  formRef.value!.resetFields()
  modelForm.value = null
  catid.value = null
}

const handleDelImg = () => {
  haveSmallImg.value = false
}

const handleModelForm = (modelForm: any) => {
  modelForm.value.modelid = modelForm.value.modelid.modelid

  delete modelForm.value.modelData
  delete modelForm.value.category_description
  delete modelForm.value.category_title
  delete modelForm.value.model

  return modelForm
}

const handleSubmit = () => {
  formRef.value
    .validate((valid: any) => {
      if (!valid) return

      modelForm.value.catid = catid.value
      const data = unref(handleModelForm(modelForm))
      props.dialogStatus === 'create' ? props.createData(data) : props.updateData(data)
      handleClose()
    })
    .catch((error: any) => {
      console.log('error', error)
    })
    .finally(() => {
      setLoading(false)
    })
}
</script>
<style lang="scss">
.app-collapse-cover {
  position: relative;
  .el-form-item {
    margin-bottom: 0;
  }
  .el-form-item__content {
    position: static;
    .el-form-item__error {
      top: 15px;
      left: 50px;
    }
  }
  .el-collapse-item__content {
    padding-bottom: 0;
  }
}
</style>
